<template>
  <el-card
    v-if="!dashboard"
    shadow="never"
    body-style="padding: 8px 20px;"
    style="margin-bottom: 4px"
  >
    <el-form :model="queryForm" size="mini" inline :class="{'spec-shop-query': specShopQuery}">
      <el-form-item
        v-if="!specShopQuery && [1,14,15].includes(app.admin.roleId)"
        label="社区"
      >
        <org-select v-model="queryForm.orgId" is-admin />
      </el-form-item>
      <el-form-item
        v-if="!specShopQuery && [1,9,14,15].includes(app.admin.roleId)"
        label="商家"
      >
        <el-select v-model="queryForm.bossId" clearable filterable style="width:100px">
          <el-option
            v-for="boss in bossPage.rows"
            :key="boss.adminId"
            :value="boss.adminId"
            :label="boss.realName"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!specShopQuery" label="店铺">
        <el-select
          v-model="queryForm.providerId"
          clearable
          filterable
          style="width:200px"
        >
          <el-option
            v-for="shop in shopPage.rows"
            :key="shop.id"
            :value="shop.id"
            :label="shop.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isTradeQueryForm" label="类型">
        <radio-options
          v-if="specShopQuery"
          v-model="queryForm.tradeType"
          :options="options.tradeType"
        />
        <type-select
          v-else
          v-model="queryForm.tradeType"
          placeholder=""
          :clearable="false"
          :items="options.tradeType"
          style="width: 86px"
        />
      </el-form-item>
      <el-form-item label="时间">
        <radio-options
          v-if="specShopQuery"
          v-model="queryForm.timeUnit"
          :options="options.timeUnit"
        />
        <type-select
          v-else
          v-model="queryForm.timeUnit"
          placeholder=""
          :clearable="false"
          :items="options.timeUnit"
          style="width: 60px"
        />
        <el-date-picker
          v-if="['day', 'month'].includes(queryForm.timeUnit)"
          v-model="queryForm.dateRange"
          :type="{day: 'daterange', month: 'monthrange'}[queryForm.timeUnit]"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width:240px"
        />
        <span v-if="queryForm.timeUnit == 'year'">
          <el-date-picker
            v-model="queryForm.dateRange[0]"
            type="year"
            :clearable="false"
            style="width:92px"
          />
          <sapn>至</sapn>
          <el-date-picker
            v-model="queryForm.dateRange[1]"
            type="year"
            :clearable="false"
            style="width:92px"
          />
        </span>
      </el-form-item>
    </el-form>
  </el-card>
</template>


<script>
import RadioOptions from '@/components/RadioOptions';
import moment from 'moment';

export default {
  components: {
    RadioOptions,
    OrgSelect: () => import('@/pages/org/OrgSelect.vue'),
  },
  props: {
    isTradeQueryForm: {
      type: Boolean,
      default: false
    },
    dashboard: {
      type: Boolean,
      default: false
    },
    dashboardQuery: {
      type: Object,
      default: null
    }
  },
  data() {
    // 路由参数
    let specShopQuery = false;
    let params = this.$parent.$vnode.context.$params;
    if (params && params.providerId) {
      specShopQuery = true;
    }

    return {
      queryForm: {
        orgId: null,
        bossId: null,
        providerId: params ? params.providerId || null : null,
        timeUnit: 'day',
        dateRange: null,
        tradeType: this.isTradeQueryForm && 3,
      },
      specShopQuery,
      options: {
        tradeType: [
          {value: 4, text: '充值额'},
          {value: 3, text: '销售额'}
        ],
        timeUnit: [
          {value: 'day', text: '日'},
          {value: 'month', text: '月'},
          {value: 'year', text: '年'}
        ]
      },
      bossPage: {},
      shopPage: {},
      app
    };
  },
  watch: {
    async 'queryForm.orgId'(orgId) {
      this.bossPage = {};

      if (orgId) {
        this.bossPage = await this.$http.get(
          '/api/shop/boss/bossPage', {params: {orgId, page: 1, rows: 10000}});
        if (this.bossPage.total == 1) {
          this.queryForm.bossId = this.bossPage.rows[0].adminId;
        } else {
          this.queryForm.bossId = null;
          this.onQuery();
        }
      } else {
        this.queryForm.bossId = null;
        this.onQuery();
      }
    },
    'queryForm.bossId'(bossId) {
      this.shopPage = {};
      if (bossId) {
        this.queryShopByBossId(bossId);
      } else {
        this.queryForm.providerId = null;
      }
    },
    'queryForm.providerId'(value) {
      this.onQuery();
    },
    'queryForm.timeUnit': {
      handler(value) {
        switch(value) {
          case 'day':
            this.queryForm.dateRange = [moment().subtract(this.dashboard ? 30 : 30, 'days'), moment()];
            break;
          case 'month':
            this.queryForm.dateRange = [moment().subtract(11, 'month'), moment()];
            break;
          case 'year':
            this.queryForm.dateRange = [moment().subtract(10, 'year'), moment()];
            break;
        }
      },
      immediate: true
    },
    'queryForm.tradeType'(value) {
      this.onQuery();
    },
    'queryForm.dateRange'(value) {
      this.onQuery();
    }
  },
  mounted() {
    if (!this.dashboard) {
      this.queryForInit();
    }
  },
  methods: {
    queryForInit() {
      switch (app.admin.roleId) {
        case 1:
        case 14:
        case 15:
          this.onQuery();
          break;
        case 2:
        case 4:
          this.queryShopByBossId();
          break;
        case 9:
          this.queryForm.orgId = app.admin.orgId;
          break;
        default:
          this.onQuery();
      }
    },
    onQuery() {
      let params = {...this.queryForm};
      if (this.dashboard && this.dashboardQuery) {
        params.dateRange = this.dashboardQuery.dateRange;
      }
      if (params.dateRange) {
        const { timeUnit } = params;
        const [ startDate, endDate ] = params.dateRange;

        // 检查范围是否合法
        if (timeUnit != 'year') {
          const TIME_DIFF_MAX = {day: 31, month: 12};
          if (moment(endDate).diff(moment(startDate), timeUnit) + 1 > TIME_DIFF_MAX[timeUnit]) {
            this.$message.warning(`按${{day:'日', month:'月',year:'年'}[timeUnit]}统计时间差不能超过${TIME_DIFF_MAX[timeUnit]}`);
            return;
          }
        }

        // 转换为字符串
        const format = ({year: 'YYYY', month: 'YYYY-MM', day: 'YYYY-MM-DD'})[timeUnit];
        params.startTime = moment(startDate).format(format);
        params.endTime = moment(endDate).format(format);
        
        delete params.dateRange;
      }

      if (!params.tradeType) {
        delete params.tradeType;
      }

      this.$emit('query', params);
    },
    async queryShopByBossId(bossId) {
      this.shopPage = await this.$http.get(
        '/api/shop/pro/proPage', {params: {bossId, page: 1, rows: 10000}});
      if (this.shopPage.total == 1) {
        this.queryForm.providerId = this.shopPage.rows[0].id;
      } else {
        this.queryForm.providerId = '';
      }
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 0px !important;
}

.spec-shop-query .el-form-item {
  margin-right: 20px;
}
</style>